/*-----------------------------------------------------------------------------------
Name: Sangyoon Park
Date: January 23 2023
This do file does : 
	Create tables for summary statistics and balance check
-----------------------------------------------------------------------------------*/
clear all
set matsize 10000
set maxvar 10000
set more off
capture log close


#delim ;

/*-----------------------------------------------------------------------------------
			 Set up
-----------------------------------------------------------------------------------*/
*** Setting up files;
	glo datafile "qu_analysis"; 	// type in the name of the datafile that you want to create;

*** Set up program;
 ** Number Format;
	capture program drop autoformat;
	program define autoformat;

	if int(`1')==`1' global format "%12.0f";
	else if abs(`1')>10 global format "%9.1f";
	else if abs(`1')>1 global format "%9.2f";
	else if abs(`1')>.1 global format "%9.3f";
	else if abs(`1')>.01 global format "%9.3f";
	else if abs(`1')>.001 global format "%9.3f";
	else if abs(`1')>.0001 global format "%9.4f";
	else if abs(`1')<.00001 global format "%9.5f";

	end;

 ** Tex Table format;
  	capture program drop head_foot;
	program define head_foot;

	syntax, [caption(str)] [label(str)] [notes(str)] [size(str)] [columns(str)] [sideways] [long];

	local estimates=r(names);
	if "`columns'"=="" local columns:word count `estimates';
	if "`sideways'"=="sideways" local table sidewaystable;
	if "`long'"=="long" local table longtable;
	else local table table;
	local col = `columns'+1;

	global header \begin{`table'}[H] \footnotesize \begin{center};
		if "`size'"!="" global header $header \begin{`size'};
		if "`caption'"!="" global header $header \caption{`caption'\label{table:`label'}} ;
		global header $header  ///;
		\begin{adjustbox}{max width=\textwidth} ///;
		\begin{threeparttable} ///;
		\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} ;
		global header $header ///;
		\begin{tabular}{l*{`columns'}{c}}\toprule[1.5pt];

	global header_mid \tabularnewline;

	global panel_title \multicolumn{`col'}{l}{Panel}\tabularnewline \midrule;

	global footer_mid \midrule ;
	global footer \bottomrule[1.2pt] ///
		\end{tabular} ;
		if "`notes'"!="" {;
			global footer $footer \begin{tablenotes}[flushleft] ///;
			`notes' ///;
			\end{tablenotes} ;
			};
		global footer $footer \end{threeparttable}\end{adjustbox};
		if "`size'"!="" global footer $footer \end{`size'};
		global footer $footer \end{center} \end{`table'} 	;
	end;


*** Set up Table option;
	loc titles "& Obs. & Mean & Median & S.D. & Min & Max \\ \midrule ";
	loc shorttitles "& Obs. & Mean & S.D. \\ \midrule ";	
	loc pesttitles " & & & & \multicolumn{4}{c}{Pr(Residue exceeds MRL)} \\ \cmidrule{5-8} ";
	loc subtitles " Pesticide (A.I.) & Obs. & Mean (mg/kg) & S.D. & E.U. & U.S. & Japan & China  \\ \midrule";
	local stat_table cells("count mean(fmt(2)) p50(fmt(2))  sd(fmt(2)) min(fmt(0)) max(fmt(0))") ///
		label noobs mlabels(none) collabels(none) nonote nonumbers posthead("`titles'") ///
		;
	local stat_shorttable cells("count mean(fmt(2)) sd(fmt(2))") ///
		label noobs mlabels(none) collabels(none) nonote nonumbers posthead("`shorttitles'") ///
		;
	local stat_balance cells("mean(fmt(2)) b(fmt(3) star)" "sd(par fmt(2)) t(par fmt(2))") ///;
			label noobs collabels(none) nonote ;
	local pest_table cells("count mean(fmt(3)) sd(fmt(3))") ///
		label noobs mlabels(none) collabels(none) nonote nonumbers posthead("`pesttitles'" "`subtitles'") ///
		;
	local overmrl_eu_table cells("mean(fmt(2))") ///
		label noobs mlabels(none) collabels(none) nonote nonumbers posthead(" & E.U. \\ \midrule") ///
		;
	local overmrl_us_table cells("mean(fmt(2))") ///
		label noobs mlabels(none) collabels(none) nonote nonumbers posthead(" & U.S. \\ \midrule") ///
		;
	local overmrl_china_table cells("mean(fmt(2))") ///
		label noobs mlabels(none) collabels(none) nonote nonumbers posthead(" & China \\ \midrule") ///
		;
	local overmrl_japan_table cells("mean(fmt(2))") ///
		label noobs mlabels(none) collabels(none) nonote nonumbers posthead(" & Japan \\ \midrule") ///
		;

		
*** Read data;
	use "${data_path}/FARMER_WIDE_SETUP", replace;	

*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);	
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	

	
/*-----------------------------------------------------------------------------------
			 Summary Statistics - Farmer
-----------------------------------------------------------------------------------*/

*** Scale Units;

	gen re_price_base = price_base/1000;
	gen re_totalvolume_base = totalvolume_base /1000;
	gen re_cost_fert_base = cost_fert_base/1000000;
	gen re_cost_pest_base = cost_pest_base/1000000;
	gen re_cost_facility_base = cost_facility_base/1000000;
	gen re_cost_equip_base = cost_equip_base/1000000;
	gen re_cost_labor_base = cost_labor_base/1000000;
	gen re_cost_utility_base = cost_utility_base/1000000;
	gen re_cost_costtotal_base = cost_costtotal_base/1000000;
	
*** Baseline variables;
	local farmersum age female edu_second exp_dragon ha_whitedragon tree_whitedragon gap_comply_base re_totalvolume_base re_price_base re_cost_costtotal_base;

	
/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var age "Age";
	lab var female "Female";
	lab var edu_second "Secondary Education";
	lab var exp_dragon "Experience growing dragon fruit (years)";
	lab var ha_whitedragon "Size of dragon fruit farm (hectares)";
	lab var tree_whitedragon "Number of dragon fruit trees";
	lab var anycert_base "Received any agricultural certificate before";
	lab var loan_any_base "Ever received loan for farm investment";
	lab var save_bank_base "Ever saved at bank";
	lab var mean_trust_base "Mean score on trust measurement";
	lab var mean_business_base "Mean score on business measurement";
	lab var mean_confidence_base "Mean score on confidence measurement";
	lab var raven_total "Raven matrices score";
	lab var present_bias_base "Time discounting - present biased";
	lab var gap_comply_base "Self-reported GAP compliance";
	lab var hours_base "Farm work hours";
	lab var re_totalvolume_base "Volume sold (tons)";
	lab var re_price_base "Average price (1,000 VND/kg)";
	lab var re_cost_fert_base "Expenses on Fertilizer (1 Million VND)";
	lab var re_cost_pest_base "Expenses on Pesticide (1 Million VND)";
	lab var re_cost_facility_base "Expenses on Facility (1 Million VND)";
	lab var re_cost_equip_base "Expenses on Equipment (1 Million VND)";
	lab var re_cost_labor_base "Expenses on Paid Labor (1 Million VND)";
	lab var re_cost_utility_base "Expenses on Utility (1 Million VND)";
	lab var re_cost_costtotal_base "Total Expenses on Inputs (1 Million VND)";
	lab var attrit_fu1 "Attrition in first follow-up survey";
	lab var attrit_fu2 "Attrition in second follow-up survey";	
	
	

 ** tabulate;
 	eststo: estpost sum `farmersum', detail; 

 ** Table;
	loc colnum 7;
	local caption Summary Statistics of Farmer Characteristics at Baseline;
	local label sum_baseline;
	local notes \item Notes: This table provides summary statistics on farmer characteristics collected from baseline survey.;

	head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum'); 	
	
	esttab using "${table_path}/sum_baseline.tex", replace ///
 	`stat_table' prehead("$header") postfoot("$footer") substitute("\_" "_");

 	est clear;


/*-----------------------------------------------------------------------------------
			 Balance Check (FOR ONLINE APPENDIX Table A-2)
-----------------------------------------------------------------------------------*/

loc sumvar age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base re_totalvolume_base re_price_base re_cost_costtotal_base attrit_fu1 attrit_fu2;

loc treat_coef dum_tgroup2-dum_tgroup8;

loc se_main cluster(group_id) robust;	

loc rows: word count `sumvar';

*** summarize;
	eststo: estpost sum `sumvar' if st_tgroup==1;
	qui esttab *, cells(mean);
	mat B1=r(coefs);
	qui esttab *, cells(sd);
	mat SE1=r(coefs);
	mat P1=J(`rows',1,.);
	est clear;

*** mean difference test;;
	mat J2=J(`rows',1,.);
	local i = 1;
	foreach var of varlist `sumvar' {;
		eststo : reg `var' `treat_coef' i.strata, `se_main';
		testparm dum_tgroup*;
		local m = r(p);
		local fmtm : di %3.2f `m';
		mat J2[`i',1]=`fmtm';
		local i = `i'+1;
	};
		esttab *, cells(b) nocons ;
		mat B2=r(coefs)';
		esttab *, cells(se) nocons;
		mat SE2=r(coefs)';
		esttab *, cells(p) nocons ;
		mat P2=r(coefs)';
		mat N2=r(stats)';
		est clear;



mat B=B1,B2;
mat SE=SE1,SE2;
mat P=P1,P2;

file open balance using "$table_path/balancecheck.tex", write replace;

file write balance 
	"\begin{table}[htbp]" _n 
	"\centering" _n 
	"\begin{scriptsize}" _n 
	"\begin{adjustbox}{max width=\textwidth}" _n 
	"\begin{threeparttable}" _n 
	"\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n 
	"\caption{Balance of Baseline Farmer Characteristics Across Treatment Groups}" _n 
	"\begin{tabular}{l*{10}{c}}" _n 
	"\toprule[1.5pt]" _n 
	"& \multicolumn{1}{c}{ }&\multicolumn{7}{c}{Mean difference}&\multicolumn{1}{c}{ } \\" _n 
	"\cmidrule(l){2-10}" _n 
	"\multicolumn{1}{r}{Certification Treatment} &\multicolumn{4}{c}{Ineligible} & \multicolumn{4}{c}{Eligible} & &  \multicolumn{1}{c}{Joint} \\" _n
	"\cmidrule(l){2-5} \cmidrule(l){6-9}" _n
	"\multicolumn{1}{r}{Training Treatment} &\multicolumn{1}{p{0.4in}}{\centering No } & \multicolumn{1}{p{0.4in}}{\centering Farmer} & \multicolumn{1}{p{0.4in}}{\centering Inter.} & \multicolumn{1}{p{0.4in}}{\centering Joint}"  
	"& \multicolumn{1}{p{0.4in}}{\centering No} & \multicolumn{1}{p{0.4in}}{\centering Farmer}" _n 
	"& \multicolumn{1}{p{0.4in}}{\centering Inter.} & \multicolumn{1}{p{0.4in}}{\centering Joint} & \multicolumn{1}{c}{N} & \multicolumn{1}{c}{p-value} \\" _n 
	"\midrule" _n
	"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)&(9)&(10) \\" _n 
	"\hline" _n;
	
	
local i 1;
foreach var in `sumvar' {;
	local label: var label `var';
	foreach j of num 1/1 {;
		local b`j'=B[`i',`j'];
		autoformat `b`j'';
		local b`j': di $format `b`j'';
		local se`j'=SE[`i',`j'];
		autoformat `se`j'';
		local se`j': di $format `se`j'';
		local se`j'=strtrim("`se`j''");
		local se`j'="[`se`j'']";
		};
	foreach j of num 2/8 {;
		local b`j'=B[`i',`j'];
		autoformat `b`j'';
		local b`j': di $format `b`j'';
		local pvalue=P[`i',`j'];
		if `pvalue'<0.01 local star ***;
		else if `pvalue'<0.05 local star **;
		else if `pvalue'<.1 local star *;
		else local star;
		if "`star'"!="" local sym "\sym{`star'}";
		else local sym;
		local b`j' `b`j''`sym';
		local se`j'=SE[`i',`j'];
		autoformat `se`j'';
		local se`j': di $format `se`j'';
		local se`j'=strtrim("`se`j''");
		if `se`j''!=. local se`j'="(`se`j'')";
		else local se`j' ;
		};
		local n = N2[`i',1];
		local fp = J2[`i',1];
	file write balance 
	"`label'&`b1'&`b2'&`b3'&`b4'&`b5'&`b6'&`b7'&`b8'&`n' & `fp' \\" _n 
	" &`se1'&`se2'&`se3'&`se4'&`se5'&`se6'&`se7'&`se8'& & \\" _n ;
	if `i'<`rows' file write balance "[1ex]"_n ; 
	local ++i ;
	};
	
file write balance 
	"\bottomrule[1.2pt]" _n 
	"\end{tabular}" _n 
	"\begin{tablenotes}[flushleft]" _n 
	"\item Notes: This table shows balance checks with farmer characteristics across randomized treatment arms. Column 1 reports average baseline characteristics for the control group" 
	" Columns 2 to 8 report OLS regression coefficients of the seven treatment indicators." 
	" * denotes significance at 0.10; ** at 0.05; and *** at 0.01." 
	" Column 10 reports the p-value from testing the joint significance of treatment indicators." _n 
	"\end{tablenotes}" _n 
	"\end{threeparttable}" _n 
	"\end{adjustbox}" _n 
	"\end{scriptsize}" _n
	"\end{table}" ;

file close balance;

	
/*-----------------------------------------------------------------------------------
			 Summary Statistics - Farmer-Intermediary Trade
-----------------------------------------------------------------------------------*/	

*** Read data;
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

*** Keep if baseline;
	keep if followup == 0;
	drop if strata == 12 | strata == 13;	

/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var buyer_exp "Years farmer has known buyer";
	lab var collector "Purchased by local collector";
	lab var exporter "Purchased by exporter";
	lab var retailer "Purchased by domestic retailer";
	lab var dum_market1 "Product for Chinese market";
	lab var dum_market2 "Product for high-price Asian market";
	lab var dum_market3 "Product for EU/US market";
	lab var dum_market4 "Product for Domestic market";
	lab var cont_formal "Trade based on formal written contract";

	
*** Baseline trade summary variables;
	local tradesum buyer_exp cont_formal collector exporter retailer dum_market1 dum_market2 dum_market3 dum_market4;
	
 ** tabulate;
 	eststo: estpost sum `tradesum', detail; 

 ** Table;
	loc colnum 7;
	local caption Summary Statistics at Baseline;
	local label sum_baseline_trade;
	local notes \item Notes: This table provides summary statistics on farmer sales transaction collected from baseline survey.;

	head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum'); 	
	
	esttab using "${table_path}/sum_baseline_trade.tex", replace ///
 	`stat_table' prehead("$header") postfoot("$footer") substitute("\_" "_");

 	est clear;
	clear;


/*-----------------------------------------------------------------------------------
			 Summary Statistics - Intermediary Data
-----------------------------------------------------------------------------------*/	

*** Read data;
	use "${data_path}/INTERMEDIARY_MERGED", replace;
	
*** Generate variables;

	gen firm_type =.;
	replace firm_type = 1 if volume_type2_fu0 != 0;
	replace firm_type = 2 if volume_type3_fu0 != 0 | volume_type4_fu0 != 0;
	replace firm_type = 3 if cooperative == 1;
	tab firm_type, gen(dum_firmtype);
	
*** Scale units;
	replace buy_avgprice_fu0 = buy_avgprice_fu0/1000;
	replace sell_avgprice_fu0 = sell_avgprice_fu0/1000;

	
	
/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var age "Years of intermediation business";
	lab var size_facility "Size of packing/collection facility $(m^2)$";
	lab var dum_firmtype1 "Type = collector";
	lab var dum_firmtype2 "Type = export enterprise";
	lab var dum_firmtype3 "Type = cooperative";
	lab var trade_volume_fu0 "Trade volume (tons)";
	lab var buy_avgprice_fu0 "Average purchase price (1,000 VND/kg)";
	lab var sell_avgprice_fu0 "Average sales price (1,000 VND/kg)";
	lab var ghp_score_fu0 "Self-reported GAP compliance";
	lab var sell_contract_fu0 "Contract with buyer";
	lab var sell_exp_fu0 "Years of experience with buyer";
	lab var volume_china_fu0 "Volume of Chinese exports (tons)";
	lab var volume_asia_fu0 "Volume of high-price Asian exports (tons)";
	lab var volume_eu_fu0 "Volume of EU/US exports (tons)";
	lab var volume_dom_fu0 "Volume of domestic sales (tons)";
	lab var cost_labor_fu0 "Expenses on labor (1M VND)";
	lab var cost_utility_fu0 "Expenses on utility (1M VND)";
	lab var cost_material_fu0 "Expenses on materials (1M VND)";
	lab var attrit_fu1 "Attrition in first follow-up survey";
	lab var attrit_fu2 "Attrition in second follow-up survey";		

	
*** Intermediary summary variables;
	local intermediary_baseline age size_facility trade_volume_fu0 buy_avgprice_fu0 ///
	sell_avgprice_fu0 cost_labor_fu0 cost_utility_fu0 cost_material_fu0;
	
 ** tabulate;
 	eststo: estpost sum `intermediary_baseline', detail; 

 ** Table;
	loc colnum 7;
	local caption Summary Statistics of Intermediary Characteristics at Baseline;
	local label sum_intermediary;
	local notes \item Notes: This table provides summary statistics on intermediary characteristics collected from baseline survey.;

	head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum'); 	
	
	esttab using "${table_path}/sum_intermediary.tex", replace ///
 	`stat_table' prehead("$header") postfoot("$footer") substitute("\_" "_");

 	est clear;
	
/*-----------------------------------------------------------------------------------
			 Balance Check (FOR ONLINE APPENDIX Table A-3)
-----------------------------------------------------------------------------------*/

	tab st_tgroup, gen(dum_tgroup);
	egen group_id = group(strata st_tgroup);
	
*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;	

*** Intermediary balance check variables;
	local sumvar age size_facility trade_volume_fu0 buy_avgprice_fu0 ///
	sell_avgprice_fu0 ghp_score_fu0 sell_contract_fu0 sell_exp_fu0 volume_china_fu0 volume_asia_fu0 ///
	volume_eu_fu0 volume_dom_fu0 cost_labor_fu0 cost_utility_fu0 cost_material_fu0 attrit_fu1 attrit_fu2;

	loc treat_coef dum_tgroup2-dum_tgroup8;	

	loc se_main cluster(group_id) robust;	

	loc rows: word count `sumvar';

*** summarize;
	eststo: estpost sum `sumvar' if st_tgroup==1;
	qui esttab *, cells(mean);
	mat B1=r(coefs);
	qui esttab *, cells(sd);
	mat SE1=r(coefs);
	mat P1=J(`rows',1,.);
	est clear;

*** mean difference test;
	mat J2=J(`rows',1,.);
	local i = 1;
	foreach var of varlist `sumvar' {;
		qui eststo: reg `var' `treat_coef' i.strata, `se_main';
		testparm dum_tgroup*;
		local m = r(p);
		local fmtm : di %3.2f `m';
		mat J2[`i',1]=`fmtm';
		local i = `i'+1;
	};
		esttab *, cells(b) nocons ;
		mat B2=r(coefs)';
		esttab *, cells(se) nocons;
		mat SE2=r(coefs)';
		esttab *, cells(p) nocons ;
		mat P2=r(coefs)';
		mat N2=r(stats)';
		est clear;



mat B=B1,B2;
mat SE=SE1,SE2;
mat P=P1,P2;

file open balance using "$table_path/balancecheck_intermediary.tex", write replace;

file write balance 
	"\begin{table}[htbp]" _n 
	"\centering" _n 
	"\begin{scriptsize}" _n 
	"\begin{adjustbox}{max width=\textwidth}" _n 
	"\begin{threeparttable}" _n 
	"\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n 
	"\caption{Balance of Baseline Exporter Characteristics Across Treatment Groups}" _n 
	"\begin{tabular}{l*{10}{c}}" _n 
	"\toprule[1.5pt]" _n 
	"& \multicolumn{1}{c}{ }&\multicolumn{7}{c}{Mean difference}&\multicolumn{1}{c}{ } \\" _n 
	"\cmidrule(l){2-10}" _n 
	"\multicolumn{1}{r}{Certification Treatment} &\multicolumn{4}{c}{Ineligible} & \multicolumn{4}{c}{Eligible} & &  \multicolumn{1}{c}{Joint} \\" _n
	"\cmidrule(l){2-5} \cmidrule(l){6-9}" _n
	"\multicolumn{1}{r}{Training Treatment} &\multicolumn{1}{p{0.4in}}{\centering No } & \multicolumn{1}{p{0.4in}}{\centering Farmer} & \multicolumn{1}{p{0.4in}}{\centering Inter.} & \multicolumn{1}{p{0.4in}}{\centering Joint}"  
	"& \multicolumn{1}{p{0.4in}}{\centering No} & \multicolumn{1}{p{0.4in}}{\centering Farmer}" _n 
	"& \multicolumn{1}{p{0.4in}}{\centering Inter.} & \multicolumn{1}{p{0.4in}}{\centering Joint} & \multicolumn{1}{c}{N} & \multicolumn{1}{c}{p-value} \\" _n 
	"\midrule" _n
	"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)&(9)&(10) \\" _n 
	"\midrule" _n;
	
	
local i 1;
foreach var in `sumvar' {;
	local label: var label `var';
	foreach j of num 1/1 {;
		local b`j'=B[`i',`j'];
		autoformat `b`j'';
		local b`j': di $format `b`j'';
		local se`j'=SE[`i',`j'];
		autoformat `se`j'';
		local se`j': di $format `se`j'';
		local se`j'=strtrim("`se`j''");
		local se`j'="[`se`j'']";
		};
	foreach j of num 2/8 {;
		local b`j'=B[`i',`j'];
		autoformat `b`j'';
		local b`j': di $format `b`j'';
		local pvalue=P[`i',`j'];
		if `pvalue'<0.01 local star ***;
		else if `pvalue'<0.05 local star **;
		else if `pvalue'<.1 local star *;
		else local star;
		if "`star'"!="" local sym "\sym{`star'}";
		else local sym;
		local b`j' `b`j''`sym';
		local se`j'=SE[`i',`j'];
		autoformat `se`j'';
		local se`j': di $format `se`j'';
		local se`j'=strtrim("`se`j''");
		if `se`j''!=. local se`j'="(`se`j'')";
		else local se`j' ;
		};
		local n = N2[`i',1];
		local fp = J2[`i',1];
	file write balance 
	"`label'&`b1'&`b2'&`b3'&`b4'&`b5'&`b6'&`b7'&`b8'&`n' & `fp' \\" _n 
	" &`se1'&`se2'&`se3'&`se4'&`se5'&`se6'&`se7'&`se8'& & \\" _n ;
	if `i'<`rows' file write balance "[1ex]"_n ; 
	local ++i ;
	};
	
file write balance 
	"\bottomrule[1.2pt]" _n 
	"\end{tabular}" _n 
	"\begin{tablenotes}[flushleft]" _n 
	"\item Notes: This table shows balance checks with intermediary characteristics across randomized treatment arms. Column 1 reports average baseline characteristics for the control group" 
	" Columns 2 to 8 report OLS regression coefficients of the seven treatment indicators." 
	" * denotes significance at 0.10; ** at 0.05; and *** at 0.01." 
	" Column 10 reports the p-value from testing the joint significance of treatment indicators." _n 
	"\end{tablenotes}" _n 
	"\end{threeparttable}" _n 
	"\end{adjustbox}" _n 
	"\end{scriptsize}" _n
	"\end{table}" ;

file close balance;

clear;
	
	

	
	
	
	
	
	
	
	
	
	
